<template>
  <div>
    <p class="title" style="">选择食品种类</p>
    <div>
      <div class="flex">
        <div class="fill">
          <el-form :model="ruleForm1" ref="ruleForm1" :rules="rules" size="small" label-width="110px" class="form">
            <el-row class="category_select">
              <el-form-item label="食品种类">
                <el-select v-model="ruleForm.leixing"  style="width:100%;">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row class="add_category_row" :class="showAddCategory? 'showEdit': ''">
              <div class="add_category">
                <el-form-item label="食品种类" prop="name1">
                  <el-input v-model="ruleForm1.name1"></el-input>
                </el-form-item>
                <el-form-item label="种类描述" prop="description">
                  <el-input v-model="ruleForm1.description"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="onSubmit('ruleForm1')">提交</el-button>
                </el-form-item>
              </div>
            </el-row>
            <div class="add_category_button" @click="addCategoryFun">
              <i class="el-icon-caret-top edit_icon" v-if="showAddCategory"></i>
              <i class="el-icon-caret-bottom edit_icon" v-else slot="icon"></i>
              <span>添加食品种类</span>
            </div>
          </el-form>
        </div>
      </div>
      <p class="title">添加食品</p>
      <div class="flex">
        <div class="fill">
          <el-form :model="foodForm" :rules="foodrules" ref="foodForm" size="mini" label-width="120px" class="demo-ruleForm">
            <el-form-item label="食品名称" prop="name">
              <el-input v-model="foodForm.name"></el-input>
            </el-form-item>
            <el-form-item label="食品活动" prop="activity">
              <el-input v-model="foodForm.activity"></el-input>
            </el-form-item>
            <el-form-item label="食品详情" prop="description">
              <el-input v-model="foodForm.description"></el-input>
            </el-form-item>
            <el-form-item label="上传食品图片" >
              <el-upload
                style=" border: 1px dashed #d9d9d9;width: 90px ;border-radius: 6px;cursor: pointer;position: relative;overflow: hidden;"
                class="avatar-uploader"
                action="http://localhost:3000/statis/addimg/food"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="食品特点">
              <el-select v-model="foodForm.attributes" multiple placeholder="请选择">
                <el-option
                  v-for="item in attributes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="食品规格">
              <el-radio class="radio" v-model="foodSpecs" label="one">单规格</el-radio>
              <el-radio class="radio" v-model="foodSpecs" label="more">多规格</el-radio>
            </el-form-item>
            <el-row v-if="foodSpecs == 'one'">
              <el-form-item label="包装费">
                <el-input-number v-model="foodForm.specs[0].packing_fee" :min="0" :max="100"></el-input-number>
              </el-form-item>
              <el-form-item label="价格">
                <el-input-number v-model="foodForm.specs[0].price" :min="0" :max="10000"></el-input-number>
              </el-form-item>
            </el-row>
            <el-row v-else style="overflow: auto; text-align: center;">
              <el-button type="primary" @click="dialogFormVisible = true" style="margin-bottom: 10px;">添加规格</el-button>
              <el-table
                :data="foodForm.specs"
                style="margin-bottom: 20px;"
                :row-class-name="tableRowClassName">
                <el-table-column
                  prop="specs"
                  label="规格">
                </el-table-column>
                <el-table-column
                  prop="packing_fee"
                  label="包装费">
                </el-table-column>
                <el-table-column
                  prop="price"
                  label="价格">
                </el-table-column>
                <el-table-column label="操作" >
                  <template slot-scope="scope">
                    <el-button
                      size="small"
                      type="danger"
                      @click="handleDelete(scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
            <el-form-item>
              <el-button type="primary" @click="addFood('foodForm')">确认添加食品</el-button>
            </el-form-item>
          </el-form>
          <el-dialog title="添加规格" :visible.sync="dialogFormVisible">
            <el-form :rules="specsFormrules" ref="specsFormrules" size="small" :model="specsForm">
              <el-form-item label="规格"  label-width="100px" prop="specs">
                <el-input v-model="specsForm.specs" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="包装费" label-width="100px">
                <el-input-number v-model="specsForm.packing_fee" :min="0" :max="100"></el-input-number>
              </el-form-item>
              <el-form-item label="价格" label-width="100px">
                <el-input-number v-model="specsForm.price" :min="0" :max="10000"></el-input-number>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="addspecs('specsFormrules')">确 定</el-button>
            </div>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {getFoodCategory, addCategory1, addFood} from '../api/getData'
  export default {
    watch:{
      // 'ruleForm.resource'(n,o){
      //  this.activeName = n
      // }
    },
    name: 'addfood',
    async created(){

      if(!this.$route.query.restaurant_id){
        this.start()
      }else{
        this.getType()

      }
    },
    mounted(){
      // console.log(document.getElementsByClassName("el-tabs__nav-scroll"))
      // document.getElementsByClassName("el-tabs__nav-scroll")[1].style.display = "none";
    },
    data () {
      return {
        img:'',
        attributes: [{
          value: '新',
          label: '新品'
        }, {
          value: '招牌',
          label: '招牌'
        },],
        foodSpecs: 'one',
        dialogFormVisible:false,
        foodForm: {
          name: '',
          description: '',
          image_path: '',
          activity: '',
          attributes: [],
          specs: [{
            specs: '默认',
            packing_fee: 0,
            price: 20,
          }],
        },
        specsForm: {
          specs: '',
          packing_fee: 0,
          price: 20,
        },
        specsFormrules: {
          specs: [
            { required: true, message: '请输入规格', trigger: 'blur' },
          ],
        },
        activeName:"单规格",
        showAddCategory:false,
        activeNames: ['1'], // 折叠面板的属性
        options: [],
        imageUrl: '',
        value: '',
        ruleForm1: {
          name1:'',
          description:''
        },
        ruleForm: {
          name: '',
          leixing: '',
          region: '',
          date1: '', // 食品详情
          delivery: false,
          type: [],
          bao:1,
          bao1:1,
        },
        foodrules: {
          name: [
            { required: true, message: '请输入食品名称', trigger: 'blur' },
          ],
        },
        rules: {
          name: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          name1:[
            { required: true, message: '请输入食品种类', trigger: 'blur' }
          ],
          description: [
            { required: true, message: '请输入食品种类描述', trigger: 'blur' }
          ]
        }
      };
    },
    methods: {
      start(){
        const h = this.$createElement;
        this.$msgbox({
          title: '消息',
          message: h('p', null, [
            h('span', null, '尚未确认商家用户 '),
            h('i', { style: 'color: teal' }, '建议先确认')
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true;
              instance.confirmButtonText = '执行中...';
              setTimeout(() => {
                done();
                setTimeout(() => {
                  instance.confirmButtonLoading = false;
                  this.$router.push({path:'shoplist'})
                }, 300);
              }, 300);
            } else {
              done();
            }
          }
        }).then(action => {
          this.$message({
            type: 'success',
            message: "请选择"
          });
        });
      },
      addFood(formName){
        if(this.$route.query.restaurant_id){
          this.$refs[formName].validate(async (valid) => {
            if (valid) {
              // console.log(this.foodForm)
              // console.log(this.$route.query.restaurant_id)
              // console.log(this.ruleForm.leixing)
              var res = await addFood({params:{
                  ...this.foodForm,
                  restaurant_id:this.$route.query.restaurant_id,
                  category_id:this.ruleForm.leixing,
                  image_path:this.img
                }})
              if(res.body.status){
                this.$message({
                  type:'success',
                  message:"添加成功"
                })
                this.$router.push("foodlist")
              }
              // console.log(res)
            }else{
              this.$message({
                type:'error',
                message:"请填写必要字段"
              })
            }
          })
        }else{
          this.start()
        }

      },
      addspecs(formName){
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            // console.log()
            this.foodForm.specs.push({ ...this.specsForm})
            this.dialogFormVisible = false
          }else{
            this.$message({
              type:'error',
              message:"请输入规格"
            })
          }
        })
      },
      tableRowClassName(row, index) {
        if (index === 1) {
          return 'info-row';
        } else if (index === 3) {
          return 'positive-row';
        }
        return '';
      },
      handleDelete(index){
        this.foodForm.specs.splice(index, 1);
      },
      handleClick(tab, event) {
        // console.log(tab, event);
      },
      addCategoryFun(){
        this.showAddCategory = !this.showAddCategory;
      },
      async getType(){
        var res = await getFoodCategory({params:{restaurant_id:this.$route.query.restaurant_id}})
        // console.log(res.body.result)
        this.options = res.body.result.map((item) => {
          return {
            label:item.name,
            value:item.id
          }
        })
      },
      async onSubmit(formName){
        // alert("123")
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            var restaurant_id = this.$route.query.restaurant_id
            var res = await addCategory1({
              params:{
                restaurant_id:restaurant_id,
                name:this.ruleForm1.name1,
                description:this.ruleForm1.description
              }
            });
            // console.log(res)
            await this.getType()
            this.ruleForm1.name1 = ''
            this.ruleForm1.description = ''
            this.showAddCategory = false
            this.$message({
              type: 'success',
              message: "提交成功"
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });

      },
      handleChange(val) { // 关于折叠面板
        console.log(val);
      },
      handleChange1(value) { // 计数器的函数
        console.log(value);
      },
      handleAvatarSuccess (res, file) { // 和上传图片相关
        console.log(res,file)
        this.img = res.filename
        this.imageUrl = URL.createObjectURL(file.raw); // 和上传图片相关
      },
      beforeAvatarUpload (file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }
    },
    submitForm(formName) { // 提交表单
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

  }
</script>

<style lang="less" scoped>
  .el-tabs__nav-scroll{
    display: none!important;
  }
  .category_select{
    border: 1px solid #eaeefb;
    padding: 10px 30px 10px 10px;
    border-top-right-radius: 6px;
    border-top-left-radius: 6px;
  }
  .add_category_row{
    height: 0;
    overflow: hidden;
    transition: all 400ms;
    background: #f9fafc;
  }
  .showEdit{
    height: 185px;
  }
  .add_category{
    background: #f9fafc;
    padding: 10px 30px 0px 10px;
    border: 1px solid #eaeefb;
    border-top: none;
  }
  .add_category_button{
    text-align: center;
    line-height: 40px;
    border-bottom-right-radius: 6px;
    border-bottom-left-radius: 6px;
    border: 1px solid #eaeefb;
    border-top: none;
    transition: all 400ms;
    &:hover{
      background: #f9fafc;
      span, .edit_icon{
        color: #20a0ff;
      }
    }
    span{
      transition: all 400ms;
    }
    .edit_icon{
      color: #ccc;
      transition: all 400ms;
    }
  }
  .el-collapse-item__content{
    background: #1d9cf8;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #000!important;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 90px;
    height: 90px;
    line-height: 90px;
    text-align: center;
  }
  .avatar {
    width: 90px;
    height: 90px;
    display: block;
  }
  .flex{
    display: flex;
    justify-content: center;
    .fill{
      width: 70%;
      padding: 12px;
      border: 1px solid #eee;
      border-radius: 7px;
      margin-top: 7px;
      box-shadow: 0px 0px 4px #999;
    }
  }
  .title{
    text-align: center;
    font-weight: 400;
    font-size: 15px;
    margin-top: 12px
  }
</style>
